package auto.app.exetion;

import auto.app.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice//全局异常处理总类
public class GlobalExceptionHandler {

    @ExceptionHandler(MainExection.class)
    public Result WoniuExection(MainExection e) {
        Result result = new Result();
        log.info(e.getCode().toString());
        log.info(e.getMsg());
        result.fail(e.getCode(), e.getMsg(), null);
        return result;
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.info(e.getMessage());
        Result result = new Result();
        result.fail(500, "服务器繁忙", null);
        return result;
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Result handleException(AccessDeniedException e) {
        log.info(e.getMessage());
        Result result = new Result();
        result.fail(500, e.getMessage(), null);
        return result;
    }

    //校验全局异常抛出
    @ExceptionHandler(BindException.class)
    public Result handleException(BindException  e){
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            StringBuilder errorMessageBuilder = new StringBuilder();
            bindingResult.getAllErrors().forEach(error -> errorMessageBuilder.append("[").append(error.getObjectName())
                    .append("-").append(error.getDefaultMessage()).append("]"));
            return Result.getInstance(String.class).setData("参数校验未通过").setCode(400).setMsg(errorMessageBuilder.toString());
        }
        return Result.getInstance(String.class).setData("参数校验未通过").setCode(400).setMsg("");
    }


    //校验全局异常抛出
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleException(MethodArgumentNotValidException  e){
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            StringBuilder errorMessageBuilder = new StringBuilder();
            bindingResult.getAllErrors().forEach(error -> errorMessageBuilder.append("[").append(error.getObjectName())
                    .append("-").append(error.getDefaultMessage()).append("]"));
            return Result.getInstance(String.class).setData("参数校验未通过").setCode(400).setMsg(errorMessageBuilder.toString());
        }
        return Result.getInstance(String.class).setData("参数校验未通过").setCode(400).setMsg("");
    }

}
